﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.WebEncoders;
using Newtonsoft.Json;
using UEditorNetCore;
using Yes.Application;
using Yes.Application.Article;
using Yes.Application.Category;
using Yes.Application.Comment;
using Yes.Application.File;
using Yes.Application.User;
using Yes.Core.Extensions;
using Yes.Domain;
using Yes.Domain.Context;
using Yes.Repository;
using Yes.Web.Blog.Attribute;
using Yes.Web.Blog.Context;

namespace Yes
{

    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddDbContext<YesDbContext>(options => options.UseSqlServer("server=.;uid=sa;pwd=123456;database=blog", b => b.UseRowNumberForPaging()));

            services.AddDbContext<YesDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Conn"), b => b.UseRowNumberForPaging()));


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options => {
                //options.Cookie.Domain = ".domain.dev";
                options.Cookie.Name = "LoginInfo";
                options.Cookie.Path = "/";
                options.LoginPath = "/Admin/Home/Login";
                options.LogoutPath = "/Admin/Home/Logout";
            });

         



            services.AddUEditorService().Add("deleteimage", context =>
            {
                context.DeleteFile();
            });

            services.AddSession();

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddTransient<IDbContext, YesDbContext>();
            services.AddTransient<IUserContext, YesUserContext>();
            

            services.AddTransient<IUserService, UserService>();
            services.AddTransient<IArticleService, ArticleService>();
            services.AddTransient<ICommentService, CommentService>();
            services.AddTransient<ICategoryService, CategoryService>();
            services.AddTransient<IFileService, FileService>();

            services.AddTransient(typeof(IRepository<>), typeof(Repository<>));

            services.AddHttpContextAccessor();

            services.AddMvc(options => {
               // options.Filters.Add(typeof(YesAuthorizeFilter));
                options.Filters.Add(new GlobalActionFilterAttribute());
            })
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            services.Configure<WebEncoderOptions>(options =>
            {
                options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            YesMapper.Initialize();


            /*
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });*/

            app.UseAuthentication();

            app.UseStaticHttpContext();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapAreaRoute(name: "areaAdmin", areaName: "Admin", template: "Admin/{controller=Home}/{action=Index}/{id?}");


                routes.MapRoute("ArchivePage", "date-{Year}-{Month}-{ArchivePage}.html", new { controller = "Article", action = "Archive" }, new { Year = @"[\d]{4}", Month = @"[\d]{1,2}", ArchivePage = @"[\d+]" }, new[] { "Yes.Web.Blog.Controllers" });

                routes.MapRoute("ArchiveMonth", "date-{Year}-{Month}.html", new { controller = "Article", action = "Archive" }, new { Year = @"[\d]{4}", Month = @"[\d]{1,2}" }, new[] { "Yes.Web.Blog.Controllers" });


                routes.MapRoute("ArchiveYear", "date-{Year}.html", new { controller = "Article", action = "Archive" }, new { Year = @"[\d]{4}" }, new[] { "Yes.Web.Blog.Controllers" });


                routes.MapRoute(
                    name: "Search",
                    template: "s.html",
                    defaults: new { controller = "Article", action = "Search" }
                );


                routes.MapRoute(
                    name: "SearchPage",
                    template: "s-{SearchPage}.html",
                    defaults: new { controller = "Article", action = "Search" }
                );


                routes.MapRoute("CategoryPage", "cate-{CategoryId}-{CategoryPage}.html", new { controller = "Article", action = "Category" }, new { CategoryId = @"[\d+]", CategoryPage = @"[\d+]" }, new[] { "Yes.Web.Blog.Controllers" });

                routes.MapRoute("Category", "cate-{CategoryId}.html", new { controller = "Article", action = "Category" }, new { CategoryId = @"[\d+]" }, new[] { "Yes.Web.Blog.Controllers" });


                routes.MapRoute("TagPage", "tag-{id}-{TagPage}.html", new { controller = "Article", action = "Tag" }, new { id = @"[\d+]", TagPage = @"[\d+]" }, new[] { "Yes.Web.Blog.Controllers" });

                routes.MapRoute("Tag", "tag-{id}.html", new { controller = "Article", action = "Tag" }, new { id = @"[\d+]" }, new[] { "Yes.Web.Blog.Controllers" });


                routes.MapRoute(
                    name: "Detail",
                    template: "article-{id}.html",
                    defaults: new { controller = "Article", action = "Detail", }
                );

                routes.MapRoute(
                    name: "GetCommentPageInfo",
                    template: "article/GetCommentPageInfo",
                    defaults: new { controller = "Article", action = "GetCommentPageInfo", }
                );

                routes.MapRoute(
                    name: "AddComment",
                    template: "article/AddComment",
                    defaults: new { controller = "Article", action = "AddComment", }
                );

                routes.MapRoute(
                    name: "IndexPage",
                    template: "page-{IndexPage}.html",
                    defaults: new { controller = "Article", action = "Index" }
                );

                routes.MapRoute(name: "default", template: "{Controller=Article}/{action=Index}/{id?}");


            });


        }
    }
}
